package com.apes.scm.settle.payment.model;

import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.util.ApesConst;
import com.apes.scm.account.account.model.Cooperation;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * 付款登记
 *
 * @author wuq
 * @create 2018-12-25 10:10
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = PaymentRegister.CONST_TABLE_NAME)
public class PaymentRegister extends Model {
    public static final String CONST_TABLE_NAME = "acc_payment_register";

    @Id
    @Column(name = "id", length = 32)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "付款登记表", padding = 5, prefix = "GF%(company)%(yy)%(month)", useDateRange = true)
    @Comment("单号")
    private String id;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id")
    @Comment("公司编码")
    private PartyRole company; //公司

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dept_id", referencedColumnName = "id")
    @Comment("部门编码")
    private Dept dept; //部门

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "partner_id", referencedColumnName = "id", nullable = false)
    @Comment("业务伙伴编码")
    private PartyRole partner; //业务伙伴

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "cooperation_id", referencedColumnName = "id")
    @Comment("合作方式编码")
    private Cooperation cooperation; //合作方式

    @States(name = "状态", values = {
            @State(id = "sent", name = "付款申请"),
            @State(id = "notPaying", name = "未付款"),
            @State(id = "executive", name = "已付款"),
            @State(id = "approve", name = "付款审核")})
    @Column(name = "state", length = 10, nullable = false)
    private String state; //状态

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "approve_uid", referencedColumnName = "id")
    @Comment("审核人")
    private PartyRole approveUID; //审核

    @Column(name = "approve_date")
    @Comment("审核日期")
    private Date approveDate; //审核日期

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "delete_uid", referencedColumnName = "id")
    @Comment("删除人")
    private PartyRole deleteUID; //删除

    @Column(name = "delete_date")
    @Comment("删除日期")
    private Date deleteDate; //删除日期

    @Column(name = "amount", nullable = false, columnDefinition = ApesConst.FIELD_16_4)
    @Comment("付款登记金额")
    private double amount = 0; //付款金额

    @Comment("源单据")
    @Column(name = "origin", length = 30)
    private String origin;

    @Comment("源单据名称")
    @Column(name = "origin_Business_Name", length = 30)
    private String originBusinessName;


    @Column(name = "account_bank", length = 32)
    @Comment("收款账户")
    private String accountBank;

    @Column(name = "bank", length = 32)
    @Comment("开户行")
    private String bank;

    @Column(name = "bank_account", length = 32)
    @Comment("开户行帐号")
    private String bankAccount;

    @Comment("支行")
    @Column(name = "subbranch", length = 200)
    private String subbranch;

    @Column(name = "note", length = 120)
    @Comment("备注")
    private String note;

    @Column(name = "type", length = 120)
    @Comment("类型")
    @States(name = "状态", values = {
            @State(id = "supplier", name = "供应商"),
            @State(id = "customer", name = "客户")})
    private String type;

    @OneToMany(mappedBy = "paymentCost", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<PaymentCost> paymentIncomeSet = new HashSet(); //付款方式

    public Set<PaymentCost> getPaymentIncomeSet() {
        if (paymentIncomeSet == null || paymentIncomeSet.isEmpty()) return new HashSet<>();
        for (PaymentCost item : paymentIncomeSet) {
            item.setPaymentCost(this);
        }
        return paymentIncomeSet;
    }

    @OneToMany(mappedBy = "paymentRegister", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<PaymentRegisterItem> paymentRegisterItem = new HashSet(); //付款单明细

    public Set<PaymentRegisterItem> getPaymentRegisterItem() {
        if (paymentRegisterItem == null || paymentRegisterItem.isEmpty()) return new HashSet<>();
        for (PaymentRegisterItem item : paymentRegisterItem) {
            item.setPaymentRegister(this);
        }
        return paymentRegisterItem;
    }


    /**
     * 计算明细金额
     */
    public void computeAmt() {
        amount = 0;
        for (PaymentRegisterItem item : paymentRegisterItem) {
            amount += item.getAmount();
        }
    }

    @Transient
    private double paymentAmount1 = 0; //实际付款

    public double getPaymentAmount1() {
        return this.paymentAmount1 = this.getPaymentRegisterItem().stream().mapToDouble(PaymentRegisterItem::getAmount).sum()
                - this.getPaymentIncomeSet().stream().mapToDouble(PaymentCost::getAmount).sum();
    }

    @Transient
    private double sumAmount1 = 0; //付款总额

    public double getSumAmount1() {
        return this.sumAmount1 = this.getPaymentRegisterItem().stream().mapToDouble(PaymentRegisterItem::getAmount).sum();
    }


    @Transient
    private PartyRole _creator;

    @Transient
    public PartyRole get_creator() {
        if (this.getCreator() == null) return null;
        return SpringManager.getBean(PartyRoleRepository.class).findOne(this.getCreator());
    }
}
